package com.appspot.checkflames.servlet;

import static com.appspot.checkflames.constants.CheckFlamesConstants.ACCESS_TOKEN_PARAM;
import static com.appspot.checkflames.constants.CheckFlamesConstants.FILTERED_FRIENDS_DETAILS;
import static com.appspot.checkflames.constants.CheckFlamesConstants.MY_GENDER;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.appspot.checkflames.bean.UserInfo;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.FacebookException;


public class CheckFlames extends HttpServlet {

	/**
	 * Generated serial version UID
	 */
	private static final long serialVersionUID = -6377252242661863919L;

	private static final Logger LOGGER = Logger.getLogger(CheckFlames.class);
	
	private static String MY_GENDER_VALUE ;
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException,ServletException {
		String accessToken = (String) req.getSession().getAttribute(ACCESS_TOKEN_PARAM);

		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
			
		List<String> friendIds = (List<String>) req.getSession().getAttribute(FILTERED_FRIENDS_DETAILS);
		
		StringBuilder uidFilter = new StringBuilder();
		for(String friendId : friendIds) {
			uidFilter.append(friendId);
			uidFilter.append(",");
		}
		String query = "select uid,first_name,last_name,pic_square,name from user where uid in (" + uidFilter.substring(0, uidFilter.length()-1) + ")";
		 
		List<UserInfo> list = null;
		try {
			list = facebookClient.executeQuery(query, UserInfo.class);
		} catch (FacebookException pException) {
			LOGGER.error("Error while fetching the friends details", pException);
		}
		if(list==null) {
			req.getSession().setAttribute(ACCESS_TOKEN_PARAM, null);
			resp.sendRedirect("/checkflames/");
			return;
		}
		MY_GENDER_VALUE = (String) req.getSession().getAttribute(MY_GENDER);
		LOGGER.info("YOUR GENDER : " + MY_GENDER_VALUE);
		updatePictureUrl(list);
		
		req.setAttribute("details", list);			
		req.setAttribute(ACCESS_TOKEN_PARAM, req.getSession().getAttribute(ACCESS_TOKEN_PARAM));
		req.getRequestDispatcher("/flamesform.jsp").forward(req, resp);
	}
	
	private void updatePictureUrl(List<UserInfo> list) {
		for(UserInfo user : list) {
			if(user.getPicture()== null || user.getPicture().equals("")) {
				if(MY_GENDER_VALUE.equals("male")) {
					user.setPicture("/images/female.jpg");
				} else {
					user.setPicture("/images/male.jpg");
				}
			}
		}
	}
}
